package com.system.base.pay;

import java.util.Map;

import org.springframework.stereotype.Component;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.system.anno.PayTemplate;
import com.system.base.ApiResult;
import com.system.config.AlipayConfig;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 支付宝支付
 * 
 * @author kaifa002
 *
 */
@SuppressWarnings("rawtypes")
@Component
@PayTemplate(code = "ali")
@Slf4j
public class AliPayTemplate extends AbstractPayTemplate {

	public AlipayClient getAlipayClient() {
		return new DefaultAlipayClient(AlipayConfig.GATEWAYURL, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY,
				"json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBULIC_KEY, AlipayConfig.SIGN_TYPE);
	}

	@Override
	public ApiResult pay(Map<String, String> params) {
		log.info("使用ali方式支付");
		AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
		AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
		// 订单描述
		model.setBody(params.get("body"));
		// 订单标题
		model.setSubject(params.get("subject"));
		// 商户订单号 就是商户后台生成的订单号
		model.setOutTradeNo(params.get("out_trade_no"));
		// 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天 (屁股后面的字母一定要带，不然报错)
		model.setTimeoutExpress(params.get("timeout_express"));
		// 订单总金额 ，默认单位为元，精确到小数点后两位，取值范围[0.01,100000000]
		model.setTotalAmount(params.get("total_amount"));
		// 禁止支付渠道
		model.setDisablePayChannels("pcredit");
		// 销售产品码 不必填
		request.setBizModel(model);
		request.setReturnUrl(AlipayConfig.RETURN_URL);
		request.setNotifyUrl(AlipayConfig.NOTIFY_URL);
		// 通过api的方法请求阿里接口获得反馈
		try {
			log.info("支付宝下单请求报文：{}", JSONUtil.parse(request));
			AlipayTradePrecreateResponse response = this.getAlipayClient().execute(request);
			log.info("支付宝下单返回报文：{}", JSONUtil.parse(response));
			if (response.isSuccess()) {
				String qrCode = response.getQrCode();
				QrConfig qrConfig = new QrConfig(300, 300);
				qrCode = QrCodeUtil.generateAsBase64(qrCode, qrConfig, "png");
				response.setQrCode(qrCode);
				return ApiResult.build(200, "下单成功！", response);
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			log.info("支付宝下单失败：", e);
		}
		return ApiResult.build(400, "下单失败！", null);
	}

	@Override
	public void packageData(Map<String, String> params) {
		log.info("ali-packageData");
		String subject = "ali充值";
		String body = "ali充值";// 商品描述，可空
		String disable_pay_channels = "creditCard,creditCardCartoon,creditCardExpress,pcredit"; // 禁用支付方式
		params.put("out_trade_no", params.get("no"));
		params.put("total_amount", "1");
		params.put("subject", subject);
		params.put("body", body);
		params.put("disable_pay_channels", disable_pay_channels);
		params.put("product_code", "FAST_INSTANT_TRADE_PAY");
		// 过期时间
		params.put("timeout_express", "30m");
	}

	@Override
	public void signature(Map<String, String> params) throws Exception {
		boolean signVerified = true;
		// boolean signVerified = signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBULIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
		// 验签失败
		if (!signVerified) {
			params.put("signature", "400");
			return;
		}
		// String trade_status = new
		// String(params.get("trade_status").getBytes("ISO-8859-1"),"UTF-8");
		params.put("trade_status", "TRADE_SUCCESS");
		String trade_status = params.get("trade_status");
		if (!"TRADE_SUCCESS".equals(trade_status)) {
			params.put("signature", "400");
			return;
		}
		params.put("signature", "200");
	}

}
